import React from 'react';
import { Form, Row, Col, Input, InputNumber, Space, Typography, Button, Empty, Tooltip } from 'antd';
import { QuestionCircleFilled } from '@ant-design/icons';
import Area from './Area';

/**
 * 标题
 */
function Title(props) {
    const { children, addButtonProps, onAdd } = props;

    return (
        <Typography.Title level={5}>
            <Space>
                {children}
                <Button {...addButtonProps} onClick={onAdd}>
                    添加
                </Button>
            </Space>
        </Typography.Title>
    );
}

/**
 * 单元格（表头）
 */
function THeaderCell(props) {
    const { label, labelInfo, span, required } = props;

    return (
        <Col span={span} style={{ padding: '8px 12px', background: '#F4F7FF' }}>
            <Space size={4}>
                {required && <span style={{ color: '#F5222D' }}>*</span>}
                {label}
                {labelInfo && (
                    <Tooltip title={labelInfo} placement="right">
                        <QuestionCircleFilled style={{ color: '#7486D9', fontSize: 12 }} />
                    </Tooltip>
                )}
            </Space>
        </Col>
    );
}

/**
 * 表头
 */
function THeader(props) {
    const { items } = props;

    return (
        <Row>
            {items.map((item) => (
                <THeaderCell key={item.name} {...item} />
            ))}
        </Row>
    );
}

/**
 * 单元格（表格体）
 */
function TBodyCell(props) {
    const { item, field, operation } = props;

    return (
        <Col span={item.span} style={{ padding: '24px 12px 0 12px', borderBottom: '1px solid #F4F7FF' }}>
            {item?.render?.(field.name, operation) || (
                <Form.Item
                    {...field}
                    name={[field.name, item.name]}
                    validateFirst={item.rules?.length > 1}
                    rules={item.rules}
                >
                    {item.children()}
                </Form.Item>
            )}
        </Col>
    );
}

/**
 * 行（表格体）
 */
function TBodyRow(props) {
    const { items, field, operation } = props;

    return (
        <Row>
            {items.map((item) => (
                <TBodyCell key={item.name} item={item} field={field} operation={operation} />
            ))}
        </Row>
    );
}

/**
 * 表格体
 */
function TBody(props) {
    const { items, fields, operation, emptyColSpan } = props;

    if (fields.length) {
        return fields.map((field) => <TBodyRow key={field.key} items={items} field={field} operation={operation} />);
    }

    return (
        <Row>
            <Col span={emptyColSpan}>
                <Empty
                    imageStyle={{ display: 'none' }}
                    description={<div style={{ paddingTop: 20, color: '#BFBFBF' }}>暂无数据</div>}
                />
            </Col>
        </Row>
    );
}

/**
 * 表单列表
 */
function FormList(props) {
    const { style, title, name, items: rawItems } = props;

    const COL_SPAN = {
        S: 1, // 开始列
        M: 4, // 中间列
        E: 2, // 结束列
    };

    const mapping = {
        input: {
            rules: [{ required: true, message: '必填' }],
            children: () => <Input autoComplete="off" placeholder="请输入" />,
        },
        inputNumber: {
            rules: [
                { required: true, message: '必填' },
                { validator: (_, value) => (value === '0' ? Promise.reject('不能为0') : Promise.resolve()) },
            ],
            children: () => (
                <InputNumber style={{ width: '100%' }} controls={false} min={0} stringMode placeholder="请输入" />
            ),
        },
    };

    const items = [
        {
            label: '序号',
            name: 'id',
            span: COL_SPAN.S,
            render: (index) => `${index + 1}`,
        },
        ...rawItems.map(({ type, ...restRawItem }) => ({
            ...mapping[type],
            ...restRawItem,
            span: COL_SPAN.M,
            required: true,
        })),
        {
            label: '操作',
            name: 'op',
            span: COL_SPAN.E,
            render: (index, operation) => (
                <Button style={{ padding: 0 }} type="link" onClick={() => operation.remove(index)}>
                    删除
                </Button>
            ),
        },
    ];

    return (
        <Form.List name={name}>
            {(fields, operation) => (
                <div style={style}>
                    <Title addButtonProps={{ disabled: fields.length >= 10 }} onAdd={() => operation.add()}>
                        {title}
                    </Title>
                    <THeader items={items} />
                    <TBody
                        items={items}
                        fields={fields}
                        operation={operation}
                        emptyColSpan={COL_SPAN.S + rawItems.length * COL_SPAN.M + COL_SPAN.E}
                    />
                </div>
            )}
        </Form.List>
    );
}

/**
 * 资源量区域
 */
function ResourceArea() {
    const computing = [
        { label: 'az', name: 'az', type: 'input' },
        { label: 'vCPU(核)', name: 'vcpu', type: 'inputNumber' },
        { label: '内存(G)', name: 'ram', type: 'inputNumber' },
    ];

    const storage = [
        {
            label: '存储集群名称',
            labelInfo: '存储集群名称：对象存储ceph集群01。',
            name: 'storageClusterName',
            type: 'input',
        },
        { label: '对应az(支持对应多个az)', name: 'az', type: 'input' },
        {
            label: '存储用途',
            labelInfo: '存储用途：如对象存储、文件存储、块存储。',
            name: 'application',
            type: 'input',
        },
        { label: '存储类型', labelInfo: '存储类型：例如超高IO块存储。', name: 'storageType', type: 'input' },
        { label: '存储总量(TB)', name: 'storageSize', type: 'inputNumber' },
    ];

    return (
        <Area
            title="新建/扩容资源量"
            info="验收资料中新建/扩容计算、存储资源量数据与云管平台计算、存储集群数据量无联动关系。"
        >
            <FormList
                style={{ marginTop: 20, marginBottom: 40 }}
                title="计算资源"
                name="calResource"
                items={computing}
            />
            <FormList style={{ marginBottom: 40 }} title="存储资源" name="storageResource" items={storage} />
        </Area>
    );
}

export default ResourceArea;
